package com.zj.utils.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.zj.utils.R;


/**
 * 弹出框
 *
 * Created by Jiang on 2019/1/15
 */
public class PopupMenu extends PopupWindow {

    private Activity activity;
    private View popView;

    @SuppressLint("InflateParams")
    public PopupMenu(Activity activity) {
        super(activity);
        this.activity = activity;
    }

    public void setPopView(int layoutId){
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        assert inflater != null;
        popView = inflater.inflate(layoutId, null);// 加载菜单布局文件
        this.setContentView(popView);// 把布局文件添加到popupWindow中
        this.setWidth(dip2px(activity, 110));// 设置菜单的宽度（需要和菜单于右边距的距离搭配，可以自己调到合适的位置）
        this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);// 获取焦点
        this.setTouchable(true); // 设置PopupWindow可触摸
        this.setOutsideTouchable(true); // 设置非PopupWindow区域可触摸
        ColorDrawable dw = new ColorDrawable(0x00000000);
        this.setBackgroundDrawable(dw);
        showAsDropDown(activity.findViewById(R.id.txtRight), 200, 20);
    }

    /**
     * 设置点击事件
     *
     * @param viewId          id
     * @param onClickListener /
     */
    public void setPopupOnClickListener(int viewId, View.OnClickListener onClickListener) {
        View view = getView(viewId);
        //dismiss();
        view.setOnClickListener(onClickListener);
    }

    /**
     * 通过viewId获取控件
     *
     * @param viewId
     * @return
     */
    private  <T extends View> T getView(int viewId) {
        View view = popView.findViewById(viewId);
        return (T) view;
    }



    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        if(Build.VERSION.SDK_INT == 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor, xoff, yoff);
    }

    // dip转换为px
    private int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

}